package com.example.emqx.controller;

import com.example.emqx.entity.DevicesEmqStatus;
import com.example.emqx.service.DevicesEmqStatusService;
import com.example.emqx.util.EmqUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * File: AuthController.java
 * Author: liufudong@szyh-smart.com
 * Date: 2024/8/29
 * Description: AuthController class.
 * 文档在https://docs.emqx.com/zh/emqx/latest/access-control/authn/http.html
 * 保存连接或断开的状态 其实这个规则主要配置mqtt发送消息给Kafka等，但是我没有外网的kafka
 */
@RestController
@RequestMapping("/mqtt")
@Slf4j
public class RuleClientController {
    @Resource
    private ObjectMapper objectMapper;
    private Map<String, Boolean> clientStatusMap = new HashMap<>();
    @Resource
    private DevicesEmqStatusService devicesEmqStatusService;

    @PostConstruct
    public void init() {
    }

    @PostMapping(path = "/rule_client")
    public void postMsg(
            @RequestBody Map<String, Object> map
    ) {
        try {
            log.info("webhook,请求体数据=:{}", objectMapper.writeValueAsString(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String event = (String) map.get("event");
        String clientId = (String) map.get("clientid");
        log.info("RuleClientController postMsg event:{}", event);
        if (event == null) {
            return;
        }
        if (event.equals("client.connected")) {
            //客户端成功接入
            savaDevicesEmqStatusService(map, 1);
        } else if (event.equals("client.disconnected")) {
            savaDevicesEmqStatusService(map, 0);
            //客户端断开连接
        }
    }

    private void savaDevicesEmqStatusService(Map<String, Object> map, int status) {
        DevicesEmqStatus devicesEmqStatus = EmqUtil.getDevicesEmqStatus(map);
        devicesEmqStatus.setStatus(status);
        boolean b = devicesEmqStatusService.saveOrUpdate(devicesEmqStatus);
        log.info("savaDevicesEmqStatusService 修改成功或失败:{}", b);
    }

    @GetMapping("/getAllStatus")
    public String getAllStatus() {
        try {
            return objectMapper.writeValueAsString(clientStatusMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
